//
//  TestViewController.m
//  苹果自带语音转文字
//
//  Created by Annie on 2020/5/11.
//  Copyright © 2020 Annie. All rights reserved.
//

#import "TestViewController.h"
#import "JKSpeechRecognizer.h"

@interface TestViewController ()<JKSpeechRecognizerDelegate>
@property (nonatomic, strong) JKSpeechRecognizer *recognizer;
@property (strong, nonatomic)  UILabel *audioTextLabel;
@end

@implementation TestViewController

#pragma mark - JKSpeechRecognizerDelegate
- (void)speechRecognizer:(JKSpeechRecognizer *)recognizer result:(SFSpeechRecognitionResult *)result error:(NSError *)error{
    if (result) {
        NSString *text= [[result bestTranscription] formattedString];//语音转文本
        [result isFinal];
        self.audioTextLabel.text = text;
    }else{
        NSLog(@"%@-%@",@"没有结果",error);
    }
}


- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.recognizer = [JKSpeechRecognizer new];
    self.recognizer.delegate = self;
    [self.recognizer requestAuthorizationWithResult:^(BOOL authorized) {
        if (authorized) {
            [self setUpUI];
        }else{
            
        }
    }];
}
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    [self.recognizer startRecognition];
}

- (void)touchesEnded:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    [self.recognizer endRecognition];
}


- (void)setUpUI{
    [self.view addSubview:self.audioTextLabel];
    self.audioTextLabel.frame = CGRectMake(0, 100, self.view.bounds.size.width, 300);
    
}


- (UILabel *)audioTextLabel{
    if (!_audioTextLabel) {
        UILabel *audioTextLabel = [UILabel new];
        audioTextLabel.numberOfLines = 2;
        audioTextLabel.backgroundColor = [UIColor yellowColor];
        _audioTextLabel = audioTextLabel;
    }
    return _audioTextLabel;
}
@end
